/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farent.solutions.plugins.stripes.hyperstripes.core.ajax;

import com.farent.solutions.plugins.stripes.hyperstripes.controller.HSPage;
import com.farent.solutions.plugins.stripes.hyperstripes.core.ComponentModel;
import com.farent.solutions.plugins.stripes.hyperstripes.core.ComponentTagHandler;
import com.farent.solutions.plugins.stripes.hyperstripes.core.ComponentTagHandlerFactory;
import java.io.IOException;
import java.io.Writer;
import javax.xml.namespace.QName;
import org.codehaus.jackson.map.ObjectMapper;

/**
 *
 * @author user
 */
public class AjaxResponseWriter {

    public static void processResponse(Writer writer, AjaxResponse ajaxResponse) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, ajaxResponse);
    }

    public static void writeInsertChange(ComponentModel component,
            HSPage page, AjaxResponse ajaxResponse) {
        ComponentTagHandlerFactory tagHandlerFactory = ComponentTagHandlerFactory.getInstance();

        //find the tagHandler
        QName qName = new QName( component.getName() );
        ComponentTagHandler tagHandler = tagHandlerFactory.getTagHandlerForTag( qName,
                component.getComponentTypeStateHelper().getHsContext() );
        //let TagHandler create the response
        AjaxResponseInsert insertResponse = tagHandler.createAjaxInsert(component, page);
        //insert it after itself so delete will remove the old one
        insertResponse.setAfter(new AjaxResponseInsert.After(component.getId()));

        //add it to the set of changes to be sent back
        ajaxResponse.getChanges().getInserts().add(insertResponse);
    }

    public static void writeDeleteChange(ComponentModel component, HSPage aThis, AjaxResponse ajaxResponse) {
        AjaxResponseDelete delete = new AjaxResponseDelete();
        delete.setId(component.getId());
        ajaxResponse.getChanges().getDeletes().add(delete);
    }

    public static void writeErrorResponse(ComponentModel component, Writer out) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public static void writeRedirectResponse(ComponentModel originComponent, Writer out) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
